#include "DataFile.h"

DataResult DataFile::readFile(const char *fileName, int lengthLine)
{
	std::string fullPath = FileUtils::getInstance()->fullPathForFilename(fileName);
	FILE *fp = fopen(fullPath.c_str(), "r");

    DataResult dr;
    
	if (!fp)
	{
		CCLOG("Can not open file %s", fullPath.c_str());
        dr.data = nullptr;
        dr.length = 0;
		return dr;
	}
 
    dr = readBuffer(fp, lengthLine);
	fclose(fp);

	return dr;
}

int DataFile::getCountLine(FILE *fp, int lengthLine)
{
	char* buf = new char[2];
	int countLine = 0;
	while (!feof(fp))
	{
		fgets(buf, lengthLine, fp);
		countLine++;

	}
	return countLine;
}

DataResult DataFile::readBuffer(FILE *fp, int lengthLine)
{
	int countLine = getCountLine(fp, lengthLine);
	char** result = new char*[countLine];
	rewind(fp);

	for (int i = 0; i < countLine; i++)
	{
		result[i] = new char[lengthLine];
		fgets(result[i], lengthLine, fp);
	}
    
    DataResult dr;
//    dr->data = new char*[countLine];
//    for (int i = 0; i < countLine; i++)
//    {
//        dr->data[i] = new char[lengthLine];
//        strcpy(dr->data[i], result[i]);
//    }
    
	dr.data = result;
	dr.length = countLine;

	return dr;
}

char* DataFile::getRow(char** data, int row)
{
	if (data == nullptr)
		return nullptr;
	char* str = data[row];
	str = strtok(str, "\r");
	str = strtok(str, "\n");
	return str;
}

DataResult DataFile::split(char* data,const char* delim)
{
    DataResult dr;
	if (data == nullptr)
    {
        dr.data = nullptr;
        dr.length = 0;
        return dr;
    }
    int dataLength= (int)strlen(data);
    char *temp = new char[50];
    strcpy(temp, data);
	temp = strtok(temp, delim);
	int length = 0;
	while (temp != NULL)
	{
		temp = strtok(NULL, delim);
		length++;
	}

	char **result = new char*[length];
	data = strtok(data, delim);
	if (length > 0)
	{
		for (int i = 0; i < length; i++)
		{
			result[i] = data;
			data = strtok(NULL, delim);
		}
	}
   
	dr.data = result;
	dr.length = length;
    
    free(temp);
    
	return dr;
}
